﻿using System.Security.Cryptography;
using System.Text;

namespace ZingFrameworkCore.Common
{
    public class Md5
    {
        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="inputstr">待加密字符串</param>
        /// <param name="len"></param>
        /// <returns>加密字符串</returns>
        public static string Crypt(string inputstr, Md5CryptType md5CryptType)
        {
            string strEncrypt = "";
            switch (md5CryptType)
            {
                case Md5CryptType.Len16:
                    strEncrypt = HashPasswordForStoringInConfigFile(inputstr).Substring(8, 16);
                    break;
                case Md5CryptType.Len32:
                    strEncrypt = HashPasswordForStoringInConfigFile(inputstr);
                    break;
            }
            return strEncrypt;
        }
        private static string HashPasswordForStoringInConfigFile(string input)
        {
            var md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString().ToUpper();
        }
    }

    public enum Md5CryptType
    {
        Len16 = 16,
        Len32 = 32
    }
}
